#include "../include/aj_tcpsever.h"

NETAPI::TcpSever::TcpSever()
{
    m_isRunning = false;
}

NETAPI::TcpSever::~TcpSever()
{
    Stop();
}

bool NETAPI::TcpSever::Start(ServerData &conf)
{
    if (m_isRunning)
    {
        return false;
    }
    //check
    conf.Verify();
    //启动线程池
    m_sessionThreads.Start(5);
    if(!this->listen(QHostAddress::Any,(quint16)conf.Port))
        return false;

    m_isRunning = true;
    return true;
}

void NETAPI::TcpSever::Stop()
{
    if (!m_isRunning)
    {
        return;
    }
    this->close();
    //关闭线程池
    m_sessionThreads.Stop();
    m_isRunning = false;
}

bool NETAPI::TcpSever::IsStart()
{
    return m_isRunning;
}

std::vector<uint32_t> NETAPI::TcpSever::GetSessionSize() const
{
    return m_sessionThreads.GetSessionSize();
}

void NETAPI::TcpSever::incomingConnection(qintptr handle)
{
    std::shared_ptr<TcpSession> session = this->CreateSession(handle);
    if (this->OnAccepted)
        this->OnAccepted(session);
}

std::shared_ptr<NETAPI::TcpSession> NETAPI::TcpSever::CreateSession(qintptr handle)
{    
    TcpThread *thread = this->m_sessionThreads.PickMinThread();
    std::shared_ptr<TcpSession> session = std::make_shared<TcpSession>(thread);
    session->setSocketDescriptor(handle);
    this->m_sessionThreads.AddSession(session);
    session->moveToThread(thread);
    if (thread)
        thread->AddOne();
    return session;
}
